package com.gengzp.common.interceptor;

import com.gengzp.common.context.MyBatisContextHolder;
import com.gengzp.common.context.TraceContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @ClassName TraceInterceptor
 * @Description 链路追踪拦截器（适配定时日志落库逻辑）
 * @Author gengzp
 * @Date 2025/9/24 11:22
 */
@Component
public class TraceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 初始化 traceId（请求头有则复用，无则后续由网关/服务生成）
        String traceId = request.getHeader("traceId");
        TraceContextHolder.setTraceId(traceId);

        // 2. 保存完整请求URL（用于链路日志上下文）
        String fullUrl = String.format("%s://%s:%s%s%s%s",
                request.getScheme(),
                request.getServerName(),
                request.getServerPort(),
                request.getContextPath(),
                request.getServletPath(),
                StringUtils.isBlank(request.getQueryString()) ? "" : "?" + request.getQueryString()
        );
        TraceContextHolder.setCurrentControllerUrl(fullUrl);

        // 3. 默认开启SQL日志打印
        MyBatisContextHolder.setPrintSqlLogFlag(true);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, @Nullable Exception ex) throws Exception {
        // 清理线程上下文变量（必须保留，避免线程池复用导致上下文污染）
        TraceContextHolder.removeTraceId();
        TraceContextHolder.removeCurrentControllerUrl();
        MyBatisContextHolder.setPrintSqlLogFlag(true); // 重置SQL日志开关
    }

}